package model.persistencia.dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;

public class HibernateUtil {

	private static final SessionFactory sessionFactory;
	private static HibernateUtil hibernateUtil;
	private static Session session;

	static {
		try {
			sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
		} catch (Throwable t) {
			throw new ExceptionInInitializerError(t);
		}
	}

	public static Session getSession() {
		if (session == null || !session.isOpen()) {
			session = sessionFactory.openSession();
		}
		return session;
	}
	
	public static HibernateUtil getInstance() {
		if(hibernateUtil == null){
			hibernateUtil = new HibernateUtil();
		}
		return hibernateUtil;
	}

	public static void closeSession() {
		session.close();
	}
	
	public static SessionFactory getSessionFactory() {
	    return sessionFactory;
	}
	
	public void startTransaction() {
		try {
			Transaction t = getSession().getTransaction(); 
			if (!t.isActive()) {
				t.begin();
			}
		} catch (RuntimeException e) {
			e.printStackTrace();
			throw e;
		}
	}

	public void commitTransaction() {
		Transaction t = getSession().getTransaction();
		t.commit();
		closeSession();
	}

	public void rollbackTransaction() {
		Transaction t = getSession().getTransaction();
		t.rollback();
		closeSession();
	}
}